import { Init, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { FlockInfoEntity } from '../entity/info';
import { FlockInfoTypeEntity } from '../entity/infoType';

/**
 * flock模块-群信息
 */
@Provide()
export class FlockInfoService extends BaseService {
  @InjectEntityModel(FlockInfoEntity)
  flockInfoEntity: Repository<FlockInfoEntity>;

  @InjectEntityModel(FlockInfoTypeEntity)
  flockInfoTypeEntity: Repository<FlockInfoTypeEntity>;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.flockInfoEntity);
  }

  async add(param: any) {
    // 调用原本的add，如果不需要可以不用这样写，完全按照自己的新增逻辑写
    let flockItem = await this.flockInfoEntity.findOneBy({ name: param.name })
    if (flockItem) {
      throw new Error('群名已存在，请修改后提交！');
    }
    const result: any = await super.add(param);
    // this.flockInfoTypeEntity.findOneBy({flockId:})
    let membersList = param.members.map(o => {
      return {
        flockId: result.id,
        flockType: 0,
        userCommentId: o
      }
    })
    let commentsList = param.comments.map(o => {
      return {
        flockId: result.id,
        flockType: 1,
        userCommentId: o
      }
    })
    let addU = membersList.concat(commentsList)
    this.flockInfoTypeEntity.save(addU)
    return result;
  }

  async update(param: any) {
    // 调用原本的add，如果不需要可以不用这样写，完全按照自己的新增逻辑写
    const result: any = await super.update(param);
    let delFlock = await this.flockInfoTypeEntity.findBy({flockId:param.id})
    let delIds = delFlock.map(o=>o.id)
    if(delIds.length){
      await this.flockInfoTypeEntity.delete(delIds)
    }
    let membersList = param.members.map(o => {
      return {
        flockId: param.id,
        flockType: 0,
        userCommentId: o
      }
    })
    let commentsList = param.comments.map(o => {
      return {
        flockId: param.id,
        flockType: 1,
        userCommentId: o
      }
    })
    let addU = membersList.concat(commentsList)
    this.flockInfoTypeEntity.save(addU)
    return result;
  }

}
